//
//  UIImageView+Fade.m
//  UIImageView+AnimationForSDWebImage
//
//  Created by 王鹏宇 on 2017/7/18.
//  Copyright © 2017年 penghe. All rights reserved.
//

#import "UIImageView+Fade.h"
#import "FileManager.h"

@implementation UIImageView (Fade)

- (void)setImageURL:(NSURL *)url placeholderImage:(UIImage *)placeholder {
    
    self.image = placeholder;
    
    @weakify(self);
    [self setImageWithURL:url placeholder:placeholder options:YYWebImageOptionSetImageWithFadeAnimation completion:^(UIImage * _Nullable image, NSURL * _Nonnull url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error) {
        @strongify(self);
        if (error) {
            self.image = [UIImageView imageFromDiskCacheForKey:url.absoluteString];
        }
    }];
    
}

+ (UIImage *)imageFromDiskCacheForKey:(NSString *)url {
    
    UIImage *image = [[YYWebImageManager sharedManager].cache getImageForKey:url];
    
    if (!image) {
        
        image = [FileManager getImageInDirectory:kPath_ImageSave url:url];
        
        if (image) {
            [[YYWebImageManager sharedManager].cache setImage:image forKey:url];
        }
    }
    
    return image;
}

+ (CGFloat)imageCacheSize {
    
    return [YYWebImageManager sharedManager].cache.diskCache.totalCost;
}

+ (void)clearImageCache {
    
    [[YYWebImageManager sharedManager].cache.diskCache removeAllObjects];
    [[YYWebImageManager sharedManager].cache.memoryCache removeAllObjects];
}

+ (void)downloadImageWithURL:(NSURL *)url progress:(YYWebImageProgressBlock)progress completion:(YYWebImageCompletionBlock)completion {
    
    [[YYWebImageManager sharedManager] requestImageWithURL:url options:kNilOptions progress:nil transform:nil completion:completion];
}

@end

